package com.mt.mtbusinessmanagementsystem.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.mt.mtbusinessmanagementsystem.constant.OSSConstant;
import com.mt.mtbusinessmanagementsystem.pojo.properties.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.management.RuntimeErrorException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
@Component
public class OSSHelperUtil {
    private OSSHelperUtil(){}
    private static OSSHelperUtil ossHelperUtil=new OSSHelperUtil();

    public static OSSHelperUtil getOssHelperUtil(){
        return ossHelperUtil;
    }

    private static OSSProperties ossProperties;
    private static OSS ossClient;
    @Autowired
    public void setOssProperties(OSSProperties ossProperties){
        OSSHelperUtil.ossProperties =ossProperties;
    }


    public String uploadFled(MultipartFile file, String directory){
        ossClient = new OSSClientBuilder().build(OSSConstant.ENDPOINT, ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        try {
            // 生成一个唯一的文件名（避免重名）
            String fileName = UUID.randomUUID().toString().replace("-", "")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 构造文件的完整Key（路径+文件名）
            String key=directory+fileName;

            // 将MultipartFile转换为File（或InputStream），这里为了简化，我们直接写入到临时文件
            Path tempFilePath = Files.createTempFile(fileName, null);
            Files.write(tempFilePath, file.getBytes());

            // 创建PutObjectRequest并上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucketName(), key, tempFilePath.toFile());
            ossClient.putObject(putObjectRequest);

            // 清理临时文件（可选，取决于你的需求）
            Files.delete(tempFilePath);

            // 返回上传后的文件URL（包含域名）
            return ossProperties.getEndpoint()+ "/" + key;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }



}
